package com.hcj.testThread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: HuangChangjin 2017-12-03 18:18
 * @Description:
 */
public class Station1 implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(Station1.class);

    private String name;
    private Lock lock = new ReentrantLock();

    public Station1(String name){
        this.name = name;
    }

    // 初始化票数
    static int tick = 20;
    static Object token = "token";
    @Override
    public void run() {
        // 同步代码块
        while (tick > 0){
//            synchronized (token){
//                if (tick > 0){
//                    log.info("线程 {} 正在出售第 {} 张票", name, tick);
//                    tick --;
//                }else{
//                    log.info("票已经买完了");
//                }
//            }

            if (lock.tryLock()){
                lock.lock();
                try {
                    if (tick > 0){
                        log.info("线程 {} 正在出售第 {} 张票", name, tick);
                        tick --;
                    }else{
                        log.info("票已经买完了");
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
        // 手动制造延迟
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        new Thread(new Station1("窗口1"), "窗口-1").start();
        new Thread(new Station1("窗口2"), "窗口-2").start();
        new Thread(new Station1("窗口3"), "窗口-3").start();
    }
}
